package com.jw.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jw.handler.BusinessException;
import com.jw.response.ResultCode;
import com.jw.system.entity.Goods;
import com.jw.system.entity.GoodsIn;
import com.jw.system.entity.InInfo;
import com.jw.system.entity.User;
import com.jw.system.entity.vo.GoodsInVO;
import com.jw.system.entity.vo.UserVO;
import com.jw.system.mapper.GoodsInMapper;
import com.jw.system.mapper.GoodsMapper;
import com.jw.system.mapper.InInfoMapper;
import com.jw.system.mapper.UserMapper;
import com.jw.system.service.GoodsInService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * <p>
 * 商品入库表 服务实现类
 * </p>
 *
 * @author jw
 * @since 2021-04-28
 */
@Service
public class GoodsInServiceImpl extends ServiceImpl<GoodsInMapper, GoodsIn> implements GoodsInService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private GoodsInMapper goodsInMapper;

    @Autowired
    private InInfoMapper inInfoMapper;

    @Autowired
    private GoodsMapper goodsMapper;

    @Override
    public Page<GoodsInVO> getGoodsInList(Integer current, Integer size, Boolean audit,GoodsInVO goodsInVO) {
        int flag = 0;
        Page<GoodsIn> page = new Page<>(current, size);
        List<Long> list = new ArrayList<>();
        QueryWrapper<GoodsIn> queryWrapper = new QueryWrapper();
        QueryWrapper<User> queryUser = new QueryWrapper();
        if (goodsInVO.getPhone() != null) {
            queryUser.like("phone", goodsInVO.getPhone());
            flag = 1;
        }
        if (goodsInVO.getUsername() != null) {
            queryUser.like("username", goodsInVO.getUsername());
            flag = 1;
        }
        if (flag == 1) {
            List<User> users = userMapper.selectList(queryUser);
            if (!users.isEmpty()) {
                for (User user : users) {
                    list.add(user.getId());
                }
                queryWrapper.in("user_id", list);
            } else {
                return new Page<>();
            }
        }
        if (goodsInVO.getInNum() != null) {
            queryWrapper.like("in_num", goodsInVO.getInNum());
        }
        if (goodsInVO.getStartTime() != null) {
            queryWrapper.ge("in_date", goodsInVO.getStartTime());
            queryWrapper.le("in_date", goodsInVO.getEndTime());
        }
        if (goodsInVO.getStaus() != null) {
            queryWrapper.eq("staus", goodsInVO.getStaus());
        }
        if(audit){
            queryWrapper.eq("staus", 0);
        }
        Page<GoodsIn> goodsInPage = goodsInMapper.selectPage(page, queryWrapper);
        List<GoodsIn> goodsIns = goodsInPage.getRecords();

        List<GoodsInVO> goodsInVOS = new ArrayList<>();
        for (GoodsIn goodsIn : goodsIns) {
            GoodsInVO goodsInVO1 = new GoodsInVO();
            BeanUtils.copyProperties(goodsIn, goodsInVO1);
            User user = userMapper.selectById(goodsIn.getUserId());
            goodsInVO1.setUsername(user.getUsername());
            User user2 = userMapper.selectById(goodsIn.getAuditorId());
            goodsInVO1.setAuditorName(user2.getUsername());
            goodsInVO1.setPhone(user.getPhone());
            goodsInVOS.add(goodsInVO1);
        }
        Page<GoodsInVO> goodsInVOPage = new Page<>();
        goodsInVOPage.setRecords(goodsInVOS);
        goodsInVOPage.setTotal(goodsInPage.getTotal());
        return goodsInVOPage;
    }

    @Override
    public Page<Goods> getDetail(Integer current, Integer size, Long id) {
        Page<InInfo> page = new Page<>(current, size);
        QueryWrapper<InInfo> queryWrapper = new QueryWrapper();
        GoodsIn goodsIn = goodsInMapper.selectById(id);
        queryWrapper.eq("in_num", goodsIn.getInNum());
        Page<InInfo> inInfoPage = inInfoMapper.selectPage(page, queryWrapper);

        List<Goods> goodsList = new ArrayList<>();
        for (InInfo inInfo : inInfoPage.getRecords()) {
            Goods goods = goodsMapper.selectById(inInfo.getGoodsId());
            goods.setNum(inInfo.getNum());
            goodsList.add(goods);
        }
        Page<Goods> goodsPage = new Page<>();
        goodsPage.setRecords(goodsList);
        goodsPage.setTotal(inInfoPage.getTotal());
        return goodsPage;
    }

    @Override
    public void add(GoodsInVO goodsInVO) {
        //随机生成入库单号
        String IN_STOCK_NUM = UUID.randomUUID().toString().substring(0, 16).replace("-", "");

        List<Object> products = goodsInVO.getProducts();

        if (!CollectionUtils.isEmpty(products)) {

            for (Object product : products) {
                LinkedHashMap item = (LinkedHashMap) product;
                //入库数量
                int productNumber = (int) item.get("productNumber");
                //物资编号
                Integer productId = (Integer) item.get("productId");
                Goods dbProduct = goodsMapper.selectById(productId);
                if (dbProduct == null) {
                    throw new BusinessException(ResultCode.PRODUCT_NOT_FOUND.getCode(),
                            ResultCode.PRODUCT_NOT_FOUND.getMessage());
                } else if (productNumber <= 0) {
                    throw new BusinessException(ResultCode.PRODUCT_IN_STOCK_NUMBER_ERROR.getCode(),
                            ResultCode.PRODUCT_IN_STOCK_NUMBER_ERROR.getMessage());
                } else {
                    //插入入库单明细
                    InInfo inStockInfo = new InInfo();
                    inStockInfo.setInNum(IN_STOCK_NUM);
                    inStockInfo.setGoodsId(dbProduct.getId());
                    inStockInfo.setNum(productNumber);
                    inInfoMapper.insert(inStockInfo);
                    //增加商品库存
                    Goods goods = goodsMapper.selectById(productId);
                    goods.setNum(goods.getNum()+productNumber);
                    goodsMapper.updateById(goods);
                }
            }

            //获取操作人信息
            Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
            String username = null;
            UserVO userVO = new UserVO();
            if (principal instanceof UserDetails) {
                username = ((UserDetails) principal).getUsername();
            } else {
                username = principal.toString();
            }
            //根据用户名查询用户信息
            LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(User::getUsername, username);
            User user = userMapper.selectOne(wrapper);

            GoodsIn goodsIn = new GoodsIn();
            goodsIn.setInDate(new Date());
            goodsIn.setUserId(user.getId());
            goodsIn.setAuditorId(goodsInVO.getAuditorId());
            goodsIn.setStaus(0);
            goodsIn.setRemark(goodsInVO.getRemark());
            goodsIn.setInNum(IN_STOCK_NUM);
            goodsInMapper.insert(goodsIn);
        } else {
            throw new BusinessException(ResultCode.PRODUCT_IN_STOCK_EMPTY.getCode(),
                    ResultCode.PRODUCT_IN_STOCK_EMPTY.getMessage());
        }

    }

    @Override
    public void getApprove(Long id) {
        GoodsIn goodsIn = goodsInMapper.selectById(id);
        goodsIn.setStaus(1);
        goodsInMapper.updateById(goodsIn);
    }
}
